package cn.itcast.service.impl;

import cn.itcast.entity.PageResult;
import cn.itcast.entity.QueryPageBean;
import cn.itcast.mapper.RoleMapper;
import cn.itcast.pojo.Permission;
import cn.itcast.pojo.Role;
import cn.itcast.service.RoleService;
import com.alibaba.dubbo.config.annotation.Service;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;


/**
 * 角色管理
 */

@Service(interfaceClass = RoleService.class)
@Transactional
public class RoleServiceImpl implements RoleService {


     @Autowired
    RoleMapper roleMapper;


    /**
     *  新增角色
     * @param role
     */
    @Override
    public void add(Role role) {

        roleMapper.add(role);

    }


    /**
     * 用户管理-查询用户角色信息
     * @return
     */
    @Override
    public List<Role> findAll() {
        return roleMapper.findAll();
    }


    /**
     * 角色管理-分页查询
     * @param queryPageBean
     * @return
     */
    @Override
    public PageResult findPage(QueryPageBean queryPageBean) {

        //当前页 每页条数
        PageHelper.startPage(queryPageBean.getCurrentPage(),queryPageBean.getPageSize());

        List<Role> list = roleMapper.findPage(queryPageBean.getQueryString());

        //反推出总条数并返回

        return new PageResult(new PageInfo(list).getTotal(),list);
    }


    /**
     * 角色管理-根据角色id查询权限信息
     * @param roleId
     * @return
     */
    @Override
    public List<Integer> findPermissionByRoleId(Integer roleId) {

        return roleMapper.findPermissionByRoleId(roleId);
    }



    /**
     * 角色管理-查询所有权限
     * @return
     */
    @Override
    public List<Permission> findAllPermission() {
        return roleMapper.findAllPermission();
    }


    /**
     * 角色管理-给角色添加权限
     * @param roleId
     * @param permissionIds
     * @return
     */
    @Override
    public void addPermission(Integer roleId, Integer[] permissionIds) {


        roleMapper.deleteById(roleId);


        if (permissionIds !=null && permissionIds.length > 0){

            for (Integer permissionId : permissionIds) {

                roleMapper.addPermission(roleId,permissionId);

            }

        }

    }

    /**
     * 角色管理-根据id删除角色
     * @param id
     * @return
     */
    @Override
    public void deleteRoleById(Integer id) {

        Integer count = roleMapper.findRoleIdAndPermissionId(id);

        Integer count2 = roleMapper.findRoleIdAndUserId(id);



        if (count > 0){

            roleMapper.deletePermissionId(id);
        }

        if (count2 > 0){

            roleMapper.deleteUserId(id);

        }

        roleMapper.deleteRoleById(id);

    }
}
